<?php
namespace Admin\Controller;
use Admin\Controller\BaseController;

class ClassController extends BaseController {

	public function index() {
		$classes = D('Class')->relation('major')->select();
		$this->assign('classes', $classes);
		$this->display();
	}

	public function add() {
		$academies = M('Academy')->select();
		$academyIdSelected = (int)$academies[0]['id'];
		$majors = M('Major')->where(array('academy_id' => $academyIdSelected))->select();
		$this->assign('academies', $academies);
		$this->assign('majors', $majors);
		$this->display();
	}

	public function addPost() {
		if(!IS_POST) {
			$this->redirect('Class/index');
		}
		$class = D('Class');
		if(!$class->create()) {
			$this->error($class->getError());
		}
		if(!$class->checkUnique($class->data())) {
			$this->error('班级已存在！');
		}
		if(!$class->add()) {
			$this->error('数据写入失败！');
		}
		$this->success('添加成功！', U('Class/index'), 0);
	}

	public function deletePost() {
		if(!IS_POST) {
			$this->redirect('Class/index');
		}
		$id = (int)I('post.id');
		$class = D('Class');
		if($class->hasChildObj($id)) {
			$this->error($class->getError());
		}
		if(M('Class')->where(array('id' => $id))->delete()) {
			$this->success('删除成功！', U('Class/index'), 0);
		} else {
			$this->error('删除失败！');
		}
	}

	public function modify() {
		$id = (int)I('id');
		$this->_detail($id);
		$this->assign('id', $id);
		$this->display();
	}

	public function modifyPost() {
		if(!IS_POST) {
			$this->redirect('Class/index');
		}
		$class = D('Class');
		if(!$class->create()) {
			$this->error($class->getError());
		}
		if(!$class->checkUnique($class->data())) {
			$this->error('班级已存在！');
		}
		$result = $class->save();
		if($result === false) {
			$this->error('数据写入失败！');
		}
		$this->success('修改成功！', U('Class/index'), 0);
	}

	public function detail() {
		$id = (int)I('id');
		$this->_detail($id);
		$this->display();
	}

	public function getMajorsByAcademyId() {
		if(IS_POST) {
			$academyId = (int)I('post.academy_id');
			$ret = M('Major')->where(array('academy_id' => $academyId))->select();
			$this->ajaxReturn($ret);
		}
		$this->redirect('Class/index');
	}

	protected function _detail($id) {
		$class = D('Class')->where(array('id' => $id))->relation('major')->find();
		$majorId = (int)$class['major']['id'];
		$major = D('Major')->where(array('id' => $majorId))->relation('academy')->find();
		$academyId = $major['academy']['id'];
		$this->assign('academy_id', $academyId);
		$this->assign('academies', M('Academy')->select());
		$this->assign('major_id', $majorId);
		$this->assign('majors', M('Major')->select());
		$this->assign('class', $class);
	}

	public function test() {
		$result = D('Class')->where(array('id' => 28))->relation('students')->select();
		dump($result);
	}

}
